package com.github.phoenics.newlives.common.exception;

import com.github.phoenics.newlives.common.base.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

/**
 * 异常工具
 *
 * @author Phoenics Chow
 * on 2019年09月24日
 */
@Slf4j
public class ApiExceptionUtils {
    private static Properties errorProperties = new Properties();
    static {
        try (InputStream baseErrorFileStream = ApiExceptionUtils.class.getClassLoader().getResourceAsStream(
                        "base-error.properties");
                InputStreamReader in = new InputStreamReader(baseErrorFileStream, "UTF-8")) {
            errorProperties.load(in);
        } catch (Exception e) {
            throw new RuntimeException("read base-error.properties file fail.", e);
        }

        try (InputStream errorFileStream = ApiExceptionUtils.class.getClassLoader()
                .getResourceAsStream("error.properties");
             InputStreamReader in = new InputStreamReader(errorFileStream, "utf-8")) {
            errorProperties.load(in);
        } catch (Exception e) {
            log.warn("can't read customer error.properties", e);
        }
    }
    public static RestResponse getApiExceptionByErrorKey(String errorKey, String... args) {
        return getErrors(errorProperties.getProperty(errorKey), args);
    }

    public static RestResponse getApiExceptionByErrorKey(String errorKey, List<String> args) {
        return getApiExceptionByErrorKey(errorKey, args.toArray(new String[]{}));
    }

    private static RestResponse getErrors(String fullMsg, String... args) {
        RestResponse restResponse=null;
        if (!StringUtils.isBlank(fullMsg)) {
            String[] msgs = fullMsg.trim().split(";");
            String reason = "";
            int code = 500;
            if (msgs.length == 2) {
                code = Integer.parseInt(msgs[0]);
                reason = msgs[1];
            } else if (msgs.length == 3) {
                String codeStr = msgs[1].toLowerCase();
                if (codeStr.startsWith("0x")) {
                    code = Integer.parseInt(codeStr.substring(2), 16);
                } else {
                    code = Integer.parseInt(codeStr, 10);
                }
                reason = msgs[2];
            }

            for (String arg : args) {
                if (arg != null) {
                    reason = StringUtils.replaceOnce(reason, "{}", arg);
                }
            }

            restResponse = RestResponse.exception(code, reason);
           // r.setTrackingId(MDC.get(BaseConstants.MDC_TRACKING_ID));
        }
        return restResponse;
    }


}
